
from rest_framework import serializers
from .models import LogistQuestion, ChoiceOption
from .models import ExamAnswer, ExamSession

class ChoiceOptionSerializer(serializers.ModelSerializer):
    """选择题选项序列化器"""
    class Meta:
        model = ChoiceOption
        fields = ['label', 'content', 'option_image']

class LogistQuestionSerializer(serializers.ModelSerializer):
    """题库题目序列化器"""
    # 如果是选择题，嵌套显示其所有选项
    options = ChoiceOptionSerializer(many=True, read_only=True)
    question_type_display = serializers.CharField(source='get_question_type_display', read_only=True)

    class Meta:
        model = LogistQuestion
        fields = [
            'id', 'question_id', 'stem', 'stem_image',
            'question_type', 'question_type_display', 'topic',
            'score', 'answer', 'suggested_time', 'options'
        ]
        
    def create(self, validated_data):
        """创建题目时的自定义逻辑"""
        # 如果没有提供question_id，自动生成一个
        if 'question_id' not in validated_data:
            import uuid
            validated_data['question_id'] = f"Q{uuid.uuid4().hex[:8]}"
        
        return super().create(validated_data)

class QuestionCreateSerializer(serializers.ModelSerializer):
    """专门用于创建题目的序列化器"""
    options = ChoiceOptionSerializer(many=True, required=False)

    class Meta:
        model = LogistQuestion
        fields = ['question_id', 'stem', 'stem_image', 'question_type', 'topic', 'score', 'answer', 'suggested_time', 'options']
        
    def create(self, validated_data):
        """创建题目和选项"""
        options_data = validated_data.pop('options', [])
        
        # 如果没有提供question_id，自动生成一个
        if 'question_id' not in validated_data:
            import uuid
            validated_data['question_id'] = f"Q{uuid.uuid4().hex[:8]}"
        
        # 创建题目
        question = LogistQuestion.objects.create(**validated_data)
        
        # 如果是选择题，创建选项
        if question.question_type == 1 and options_data:
            for option_data in options_data:
                ChoiceOption.objects.create(question=question, **option_data)
        
        return question

class ExamAnswerSerializer(serializers.ModelSerializer):
    question_id = serializers.CharField(source='question.question_id', read_only=True)
    correct_answer = serializers.CharField(source='question.answer', read_only=True)
    question_score = serializers.IntegerField(source='question.score', read_only=True)
    
    class Meta:
        model = ExamAnswer
        fields = ['question_id', 'user_answer', 'is_correct', 'score_earned', 
                 'answered_at', 'correct_answer', 'question_score']
        read_only_fields = ['is_correct', 'score_earned', 'answered_at']

class ExamSessionSerializer(serializers.ModelSerializer):
    answers = ExamAnswerSerializer(many=True, read_only=True)
    
    class Meta:
        model = ExamSession
        fields = ['session_id', 'created_at', 'total_score', 'is_completed', 'answers']
        read_only_fields = ['created_at', 'total_score', 'is_completed']